package com.cyjf.api;


import net.sf.json.JSONObject;
import org.apache.commons.httpclient.*;
import org.apache.commons.httpclient.Header;
import org.apache.commons.httpclient.HttpException;
import org.apache.commons.httpclient.HttpStatus;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.http.*;
import org.apache.http.StatusLine;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpUriRequest;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.impl.client.HttpClients;

import org.apache.http.util.EntityUtils;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.io.IOException;
import java.util.*;

/**
 * Created by liqun.chen on 2017/5/15.
 */
@Component
@EnableScheduling
public class HttpUtil {


    /**
     * json 字符串
     *
     * @param url
     * @param param
     * @return
     */
    public static String getSerchPersion(String url, String param) {
      /* 1 生成 HttpClinet 对象并设置参数 */
        HttpClient httpClient = new HttpClient();
        // 设置 Http 连接超时为5秒
        httpClient.getHttpConnectionManager().getParams().setConnectionTimeout(15000);
      /* 2 生成 GetMethod 对象并设置参数 */
//        GetMethod getMethod = new GetMethod(url);
        PostMethod postMethod = new PostMethod(url);



        // 设置 get 请求超时为 5 秒
//        getMethod.getParams().setParameter(HttpMethodParams.SO_TIMEOUT, 5000);
        // 设置请求重试处理，用的是默认的重试处理：请求三次
//        getMethod.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler());
        String response = "";
      /* 3 执行 HTTP GET 请求 */
        try {
            int statusCode = httpClient.executeMethod(postMethod);
         /* 4 判断访问的状态码 */
            if (statusCode != HttpStatus.SC_OK) {
                System.err.println("请求出错: " + postMethod.getStatusLine());
            }
         /* 5 处理 HTTP 响应内容 */
            // HTTP响应头部信息，这里简单打印
            Header[] headers = postMethod.getResponseHeaders();
            for (Header h : headers)
                System.out.println(h.getName() + "------------ " + h.getValue());
            // 读取 HTTP 响应内容，这里简单打印网页内容
            byte[] responseBody = postMethod.getResponseBody();// 读取为字节数组
            response = new String(responseBody, param);
            System.out.println("----------response:" + response);
            // 读取为 InputStream，在网页内容数据量大时候推荐使用
            // InputStream response = getMethod.getResponseBodyAsStream();
        } catch (HttpException e) {
            // 发生致命的异常，可能是协议不对或者返回的内容有问题
            System.out.println("请检查输入的URL!");
            e.printStackTrace();
        } catch (IOException e) {
            // 发生网络异常
            System.out.println("发生网络异常!");
            e.printStackTrace();
        } finally {
         /* 6 .释放连接 */
            postMethod.releaseConnection();
        }
        return response;
    }

    /**
     * post请求（用于请求json格式的参数）
     * @param url
     * @param params
     * @return
     */
    public static String doPost(String url, String params) throws Exception {

        RequestConfig config = RequestConfig.custom().setSocketTimeout(7000).build();
//        CloseableHttpClient  httpClient = HttpClientBuilder.create().setDefaultRequestConfig(config).build();
        CloseableHttpClient  httpClient = HttpClientBuilder.create().build();
        HttpPost httpPost = new HttpPost(url);// 创建httpPost
//        httpPost.setHeader("Accept", "application/json");
        httpPost.setHeader("Content-Type", "application/json");
        String charSet = "UTF-8";
        StringEntity entity = new StringEntity(params, charSet);
        httpPost.setEntity(entity);
        httpPost.setConfig(config);
        CloseableHttpResponse response = null;

        try {
            response = httpClient.execute(httpPost);

           StatusLine status = response.getStatusLine();
            int state = status.getStatusCode();
            if (state == HttpStatus.SC_OK) {
                HttpEntity responseEntity = response.getEntity();
                String jsonString = EntityUtils.toString(responseEntity);
                return jsonString;
            }

        }
         finally {
            if (response != null) {
                try {
                    response.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            try {
                httpClient.close();
            } catch (IOException e) {
                    e.printStackTrace();
            }
        }
        return null;
    }

//    /**
//     * post请求
//     * @param url
//     * @param json
//     * @return
//     */
//    public static JSONObject doPost(String url,JSONObject json){
//        DefaultHttpClient client = new DefaultHttpClient();
//        HttpPost post = new HttpPost(url);
//        JSONObject response = null;
//        try {
//            StringEntity s = new StringEntity(json.toString());
//            s.setContentEncoding("UTF-8");
//            s.setContentType("application/json");//发送json数据需要设置contentType
//            post.setEntity(s);
//            HttpResponse res = client.execute(post);
//            if(res.getStatusLine().getStatusCode() == HttpStatus.SC_OK){
//                HttpEntity entity = res.getEntity();
//                String result = EntityUtils.toString(entity);// 返回json格式：
//                response = JSONObject.fromObject(result);
//            }
//        } catch (Exception e) {
//            throw new RuntimeException(e);
//        }
//        return response;
//    }






    //调用
    public static void main(String arg[]) throws Exception {
//        String url = "http://localhost:20100/spring-boot/cert/loginUser";
//        String url = "http://localhost:8080/carDealer/count";
        String url = "http://localhost:8080/staff/staffGMV";
        JSONObject params = new JSONObject();
//        params.put("loginName", "wy");
//        params.put("loginPwd", "123456");
//        params.put("contractNo", "netsign,contract,issue");
//        params.put("startDate", "20171120");
//        params.put("endDate", "20171227");
//        params.put("contractNo", "trxd-20180011");
//        params.put("loan_cate", "530001");
//        params.put("customerName", "张三");
//        params.put("certificate_type", "150001");
//        params.put("certificateNo", "510211198505022301");
//        params.put("contractAmount", "100000");3
//        params.put("intRate", "10");
//        params.put("contractSignDate", "20180411");
//        params.put("issueDate", "20171220");

//        params.put("offset", "0");
//        params.put("limit", "3");
//        params.put("name", "同盾");

        //get 请求
//        String ret = getSerchPersion(url, param.toString());
//        System.out.println(ret);
//        JSONObject jsonResponse=JSONObject.fromObject(param);
//        JSONObject json = (JSONObject)jsonResponse.get("page");
//        System.out.println(json.get("pageSize"));

        //post 请求
        String jsonObject = doPost(url,params.toString());
        System.out.println(jsonObject.toString());
    }


}
